<template>
	<view class="regest-content">
		<form @submit="formSubmit" @reset="formReset" ref="form">
		<view class="sub-title">小区信息</view>
		<tui-list-cell :arrow="true" @click="show = true">
			<view class="tui-line-cell">
				<view class="tui-title required"><text>市</text><text>/</text><text>区</text></view>
				<view class="picker">
					{{areaName || '请选择市/区'}}
				</view>
			</view>
		</tui-list-cell>
		<tui-list-cell :arrow="true">
			<view class="tui-line-cell" @click="chooseCommunityName">
				<view class="tui-title required"><text>小</text><text>区</text><text>名</text><text>称</text></view>
				<view class="picker">
					{{communityName || '请选择小区名称'}}
				</view>
			</view>
		</tui-list-cell>
		<view class="sub-title">业主信息</view>
		<tui-list-cell>
			<view class="tui-line-cell">
				<view class="tui-title required">
					<text>用</text><text>户</text><text>名</text>
				</view>
				<input placeholder-class="tui-phcolor" 
				class="tui-input" 
				name="name" 
				:value="userInfo.userName"
				placeholder="请输入用户名" 
				maxlength="50" type="text" />
			</view>
		</tui-list-cell>
		<tui-list-cell>
			<view class="tui-line-cell">
				<view class="tui-title required"><text>身</text><text>份</text><text>证</text></view>
				<input placeholder-class="tui-phcolor" 
				class="tui-input" 
				name="idcard" 
				:value="userInfo.idCard"
				placeholder="请输入身份证号码" maxlength="50" type="text" />
			</view>
		</tui-list-cell>
		<tui-list-cell>
			<view class="tui-line-cell">
				<view class="tui-title required"><text>手</text><text>机</text><text>号</text></view>
				<input placeholder-class="tui-phcolor" 
				class="tui-input" 
				name="mobile" 
				v-model="mobile"
				placeholder="请输入手机号" maxlength="50" type="text" />
			</view>
		</tui-list-cell>
		<tui-list-cell>
			<view class="tui-line-cell">
				<view class="tui-title required"><text>验</text><text>证</text><text>码</text></view>
				<input placeholder-class="tui-phcolor"
				class="tui-input" 
				name="vcode" 
				placeholder="请输入验证码" maxlength="50" type="text" />
				<tui-button size="mini" :type="type" shape="circle" :plain="true" :disabled="disabled" @click="btnSend">{{btnText}}</tui-button>
			</view>
		</tui-list-cell>
		<view class="tui-footer">
			<tui-button 
			class="tui-btn tui-danger tui-fillet" 
			hover-class="tui-danger-hover" formType="submit">绑定业主</tui-button>
		</view>
		</form>
		<tui-bottom-popup
		 :show="show" backgroundColor="transparent" @close="close">
			<tui-cascade-selection 
			:size="26" :textSize="24" 
			:itemList="areaList" :reset="reset" 
			@complete="complete"></tui-cascade-selection>
		</tui-bottom-popup>
	</view>
</template>

<script>
	import tuiListCell from "@/components/list-cell/list-cell"
	import tuiButton from "@/components/button/button"
	import tuiCascadeSelection from "@/components/tui-cascade-selection/tui-cascade-selection"
	import tuiBottomPopup from "@/components/tui-bottom-popup/tui-bottom-popup"
	const form = require("@/components/utils/formValidation.js")
	import Java110Context from '@/context/Java110Context.js'
	const util = require('../../utils/util.js')
	import constant from "@/constant"
	export default{
		components: {
			tuiListCell,
			tuiCascadeSelection,
			tuiBottomPopup,
			tuiButton
		},
		data() {
			return {
				pageData:{},
				btnText: "获取验证码",
				disabled: false,
				type: "primary",
				mobile: '',
				show: false,
				reset: 0,
				areaName: '',
				areaCode: '',
				communityName:'',
				areaObjectPage: {},
				areaList: []
			}
		},
		computed:{
			userInfo(){
				let us = {}
				try{
					us = uni.getStorageSync(this.java110Constant.mapping.USER_INFO);
					us = this.java110Util.des.desDecrypt(us)
					us = JSON.parse(us)
					console.log(us)
				}catch(e){
					//TODO handle the exception
				}
				return us
			}
		},
		mounted(){
			let _that = this;
			let _location = Java110Context.getLocation();
			let _currentLocation = Java110Context.getCurrentLocation();
			let _areaName = _currentLocation.city + _currentLocation.district;
			let _areaCode = _currentLocation.adcode;
			//加载省份
			this.mobile = this.userInfo.link;
			Java110Context._loadArea('', '', function(_areaList) {
			  _that.areaObjectPage = _areaList;
			  let province_list = Object.keys(_areaList.province_list).map(key => {
				  return {
					  text: _areaList.province_list[key],
					  id: key,
					  value: key,
					  children: _that.getChildren(_areaList, 'city_list', key, 2)
				  }
			  })
		      _that.areaList = province_list;
			  _that.communityName = _location;
			  _that.areaCode = _areaCode;
			  _that.areaName = _areaName;
			});
		},
		methods:{
			getChildren(obj, key, id, sub){
				let list = Object.keys(obj[key]);
				let sublist = list.filter(item => {
					return item.substr(0, sub) === id.substr(0,sub)
				})
				return sublist.map(item => {
					return {
						text: obj[key][item],
						id: item,
						value: item,
						children: (sub === 4)?[]:this.getChildren(obj, 'county_list', item, 4)
					}
				})
			},
			chooseCommunityName(){
				if(!this.areaCode){
					this.tui.toast("请先选择市/区");
					return
				}
				uni.navigateTo({
					url:'/pages/regest/regestList?areaCode=' + this.areaCode
				})
			},
			close(){
				this.show=false
			},
			complete(e){
				// console.log(e);
				this.areaCode = e.value;
				this.areaName = e.result.map(item => item.text).join('/');
				this.communityName = '';
				this.close();
			},
			PickerChange(){
				
			},
			formSubmit(e){
				//表单规则
				let rules = [{
					name: "name",
					rule: ["required", "minLength:2", "maxLength:10"], //可使用区间，此处主要测试功能
					msg: ["请输入用户名", "用户名必须2个或以上字符", "用户名不能超过10个字符"]
				},{
					name: "mobile",
					rule: ["required", "isMobile"],
					msg: ["请输入手机号", "请输入正确的手机号"]
				},{
					name: "idcard",
					rule: ["required", "isIdCard"],
					msg: ["请输入身份证号码", "请输入正确的身份证号码"]
				}];
				//进行表单检查
				let formData = e.detail.value;
				if(!this.areaCode){
					this.tui.toast("请选择市/区");
					return
				}
				if(!this.communityName){
					this.tui.toast("请选择小区名称");
					return
				}
				let obj = {
				      "areaCode": this.areaCode,
				      "communityName": this.communityName,
				      "appUserName": formData.name,
				      "idCard": formData.idcard,
				      "link": formData.mobile,
				      "msgCode": formData.vcode,
				    }
				let checkRes = form.validation(formData, rules);
				const _that = this;
				if (!checkRes) {
					 uni.showLoading({
					        title: '绑定中...',
					      });
						  // console.log(constant.url.appUserBindingOwner)
					      Java110Context.request({
					        url: constant.url.appUserBindingOwner,
					        header: Java110Context.getHeaders(),
					        method: "POST",
					        data: obj, //动态数据
					        success: function(res) {
					          console.log(res);
					          //成功情况下跳转
					          if (res.statusCode == 200 && !res.data.message) {
					            uni.hideLoading();
								uni.showToast({
								  title: '绑定成功',
								  duration: 2000
								});
					            uni.navigateBack({
					                delta: 1,
					            })
					            return;
					          }
					          uni.hideLoading();
							  _that.tui.toast(res.data || res.data.message);
					        },
					        fail: function(e) {
					          uni.hideLoading();
					          _that.tui.toast("服务气异常了");
					        }
					      });
				} else {
					uni.showToast({
						title: checkRes,
						icon: "none"
					});
				}
			},
			formReset(e){
				
			},
			getRandom: function(seconds) {
				uni.showLoading({
					mask: true,
					title: '请稍候...'
				})
				const _that = this;
				let obj = {
				      tel: this.mobile
				};
				// return new Promise((resolve,reject) => {
					Java110Context.request({
					      url: constant.url.userSendSms,
					      header: Java110Context.getHeaders(),
					      method: "POST",
					      data: obj, //动态数据
					      success: function(res) {
					        //成功情况下跳转
					        if (res.statusCode == 200) {
					          uni.hideLoading()
					          _that.doLoop(seconds);
					          return;
					        }
							_that.btnText = "获取验证码";
							_that.disabled = false;
							_that.type = "primary";
					        uni.hideLoading()
					        uni.showToast({
					          title: res.data,
					          icon: 'none',
					          duration: 2000
					        });
					      },
					      fail: function(e) {
							  _that.btnText = "获取验证码";
							  _that.disabled = false;
							  _that.type = "primary";
					        uni.hideLoading()
					        _that.tui.toast("服务器异常了")
					      }
					    });
				// })
				
			},
			doLoop: function(seconds) {
				// let code = this.getRandom(6);
				// this.tui.toast('您本次的验证码是：' + code, 5000);
				seconds = seconds ? seconds : 60;
				this.btnText = seconds + "s后获取";
				// this.code = code
				let countdown = setInterval(() => {
					if (seconds > 0) {
						this.btnText = seconds + "s后获取"
							--seconds;
					} else {
						this.btnText = "获取验证码";
						this.disabled = false;
						this.type = "primary";
						clearInterval(countdown);
					}
				}, 1000);
			},
			btnSend: function() {
				if (util.isNullOrEmpty(this.mobile)) {
					this.tui.toast('请输入手机号码');
					return
				} else if (!util.isMobile(this.mobile)) {
					this.tui.toast('请输入正确的手机号码');
					return
				}
				this.disabled = true;
				this.btnText = "请稍候...";
				this.type = "gray"
			
				// setTimeout(() => {
				this.getRandom(60)
				// }, 500)
			},
		}
	}
</script>

<style lang="scss">
	.regest-content{
		height: 100%;
		overflow-y: auto;
		padding-bottom: 10upx;
		padding-top: 30upx;
		box-sizing: border-box;
		position: relative;
		background-color: rgb(247, 249, 251);
		.sub-title{
			  margin: 0;
			  font-weight: 400;
			  font-size: 28upx;
			  color: rgba(69,90,100,.6);
			  padding: 40upx 30upx 20upx;
		}
		.tui-footer{
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			padding: 30upx 40upx;
			background-color: #FFFFFF;
		}
		.tui-btn-box {
			padding: 40upx 50upx;
			box-sizing: border-box;
		}
		.tui-line-cell {
			width: 100%;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			input{
				flex: 1;
			}
			.tui-title {
				line-height: 32upx;
				margin-right: 20upx;
				flex-shrink: 0;
				width: 180upx;
				display: flex;
				justify-content: space-between;
				text-align: justify;
			}
		}
		.picker{
			flex: 1;
			margin-right: 20upx;
			text-align: right;
		}
	}
</style>
